package com.ahm.server.service.impl;

import com.ahm.server.pojo.Admin;
import com.ahm.server.pojo.Menu;
import com.ahm.server.mapper.MenuMapper;
import com.ahm.server.service.IMenuService;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.redis.core.RedisTemplate;
import org.springframework.data.redis.core.ValueOperations;
import org.springframework.security.core.context.SecurityContextHolder;
import org.springframework.stereotype.Service;
import org.springframework.util.CollectionUtils;

import java.util.List;

/**
 * <p>
 *  服务实现类
 * </p>
 *
 * @author ahm
 * @since 2021-09-23
 */
@Service
public class MenuServiceImpl extends ServiceImpl<MenuMapper, Menu> implements IMenuService {

    @Autowired(required = false)
    private MenuMapper menuMapper;

    @Autowired
    private RedisTemplate<String,Object> redisTemplate;

/**
　　* @description: 根据ID查询对应的菜单
　　* @param ${tags}
　　* @return ${return_type}
　　* @throws
　　* @author anhaimeng
　　* @date 2021/9/23 19:50
　　*/
    @Override
    public List<Menu> getMenusByAdminId() {
        Admin admin = (Admin) SecurityContextHolder.getContext().getAuthentication().getPrincipal();
        Integer id = admin.getId();
        ValueOperations<String, Object> operations = redisTemplate.opsForValue();
        List<Menu> menus = (List<Menu>) operations.get("menu_" + id);
        if (CollectionUtils.isEmpty(menus)){
             menus = menuMapper.getMenusByAdminId(id);
             // 放入redis中
            operations.set("menu_"+id,menus);
        }
        return menus;
    }

    @Override
    public List<Menu> getAllMenusWithRole() {
        return menuMapper.getAllMenusWithRole();
    }
}
